//
//  WPYBindingPhoneVC.m
//  wobingwoyi
//
//  Created by WGP on 2016/12/16.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPYBindingPhoneVC.h"
#import "WLCaptcheButton.h"
#import "WPBingZFBVC.h"
#import "WPBingYLVC.h"

@interface WPYBindingPhoneVC ()

@property(nonatomic,strong)UIView *bgView;
@property(nonatomic,strong)UIButton *doneBtn;
@property(nonatomic,strong)UITextField *phoneField;
@property(nonatomic,strong)UITextField *verifiedField;
@property (nonatomic,strong)WLCaptcheButton *captcheButton;

@property(nonatomic,assign)BOOL isVerified;

@end

@implementation WPYBindingPhoneVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.titleLabel.text = @"兑换收益";
    self.view.backgroundColor = GlobalBgColor;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
    [self.rightBtn setTitle:@"取消" forState:UIControlStateNormal];
    
    [self bgView];
    [self doneBtn];
    
    WPUserAccountViewModel *userAccountModel = [WPUserAccountViewModel sharedInstance];
    WPUserAccount *userAccount = userAccountModel.userAccount;
    if (userAccount.user.phone.length)
    {
        self.phoneField.text = userAccount.user.phone;
    }
}

-(UIView *)bgView
{
    if (_bgView == nil)
    {
        _bgView = [UIView new];
        _bgView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_bgView];
        
        [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.navBarView.mas_bottom).offset(10);
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(88);
        }];
        
        self.phoneField = [UITextField new];
        self.verifiedField = [UITextField new];
        self.phoneField.placeholder = @"请输入手机号码";
        self.verifiedField.placeholder = @"请输入验证码";
        self.phoneField.font = [UIFont systemFontOfSize:15];
        self.verifiedField.font = [UIFont systemFontOfSize:15];
        self.phoneField.textColor = GLobalFontColor;
        self.verifiedField.textColor = GLobalFontColor;
        self.phoneField.keyboardType = UIKeyboardTypePhonePad;
        self.verifiedField.keyboardType = UIKeyboardTypeNumberPad;
        [_bgView addSubview:self.phoneField];
        [_bgView addSubview:self.verifiedField];
        
        [_bgView addSubview:self.phoneField];
        [_bgView addSubview:self.verifiedField];
        
        [self.phoneField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_bgView).offset(15);
            make.top.right.equalTo(_bgView);
            make.height.mas_equalTo(44);
        }];
        
        _captcheButton = [WLCaptcheButton new];
        _captcheButton.identifyKey = @"WPYBindingPhoneVC";
        _captcheButton.disabledTitleColor = GloballightFontColor;
        [_captcheButton sizeToFit];
        _captcheButton.titleLabel.font = [UIFont systemFontOfSize:13];
        [_captcheButton setTitleColor:GlobalColor forState:UIControlStateNormal];
        [_captcheButton addTarget:self action:@selector(getVerifyCodeBtn:) forControlEvents:UIControlEventTouchDown];
        [_captcheButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_bgView addSubview:_captcheButton];
        
        CGSize size = [_captcheButton.titleLabel.text sizeWithMaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT) font:13];
        [_captcheButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_bgView).offset(-10);
            make.bottom.equalTo(_bgView);
            make.height.mas_equalTo(44);
            make.width.mas_equalTo(size.width+2);
        }];
        
        UIImageView *line = [UIImageView lineImageView];
        [_bgView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_captcheButton);
            make.width.mas_equalTo(0.5);
            make.height.mas_equalTo(24);
            make.right.equalTo(_captcheButton.mas_left).offset(-10);
        }];
        
        [self.verifiedField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.height.equalTo(self.phoneField);
            make.top.equalTo(self.phoneField.mas_bottom);
            make.right.equalTo(line).offset(-10);
        }];
        
        UIImageView *lineView1 = [UIImageView lineImageView];
        UIImageView *lineView2 = [UIImageView lineImageView];
        UIImageView *lineView3 = [UIImageView lineImageView];
        [_bgView addSubview:lineView1];
        [_bgView addSubview:lineView2];
        [_bgView addSubview:lineView3];
        
        lineView1.frame = CGRectMake(0, 0, SCREEN_WIDTH, 0.5);
        lineView2.frame = CGRectMake(15, 44-0.5, SCREEN_WIDTH-15, 0.5);
        lineView3.frame = CGRectMake(0, 88-0.5, SCREEN_WIDTH, 0.5);
    }
    return _bgView;
}

-(UIButton *)doneBtn
{
    if (_doneBtn == nil)
    {
        WPUserAccountViewModel *userAccountModel = [WPUserAccountViewModel sharedInstance];
        WPUserAccount *userAccount = userAccountModel.userAccount;
        
        NSString *title = nil;
        if (userAccount.user.phone.length)
        {
            title = @"完成";
        }
        else
        {
            title = @"绑定";
        }
        _doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_doneBtn setBackgroundImage:[UIImage imageNamed:@"normal"] forState:UIControlStateNormal];
        [_doneBtn setBackgroundImage:[UIImage imageNamed:@"highLight"] forState:UIControlStateHighlighted];
        [_doneBtn setTitle:title forState:UIControlStateNormal];
        _doneBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [self.view addSubview:_doneBtn];
        [_doneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.bgView.mas_bottom).offset(80);
            make.left.equalTo(self.view).offset(20);
            make.right.equalTo(self.view).offset(-20);
        }];
        [_doneBtn addTarget:self action:@selector(exchangeEarningsBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
        
        UILabel *tipLabel = [UILabel new];
        tipLabel.text = @"验证手机号以保障您的账号安全";
        tipLabel.textColor = RGB_SAME(153);
        tipLabel.font = [UIFont systemFontOfSize:12];
        [self.view addSubview:tipLabel];
        [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(_doneBtn.mas_bottom).offset(20);
        }];
    }
    return _doneBtn;
}

-(void)getVerifyCodeBtn:(WLCaptcheButton *)sender
{
    if (![NSString isMobile:self.phoneField.text])
    {
        [self showErrorInfoWithStatus:@"手机号码格式不正确"];
        return ;
    }
    
    [self showWithStatus:@"正在发送"];
    
    NSString *url = @"user/sendMessage.do";
    NSDictionary *dict = @{@"telephone":self.phoneField.text};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self dismiss];
        
        if ([responseObject[@"result"] isEqualToString:@"success"])
        {
            self.isVerified = NO;
            
            [self showSuccessInfoWithStatus:@"验证码已发送至手机"];
            [sender fire];
        }
        else
        {
            [self showErrorInfoWithStatus:@"获取失败"];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self dismiss];
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

-(void)exchangeEarningsBtnDidClick
{
    [self.view endEditing:YES];
    
    if (!(self.phoneField.text.length && self.verifiedField.text.length))
    {
        [self showErrorInfoWithStatus:@"手机号或验证码不能为空"];
        return ;
    }
    
    if (self.isVerified)
    {
        [self showErrorInfoWithStatus:@"请重新获取验证码"];
        return ;
    }
    
    [self showWithStatus:nil];
    
    WPUserAccountViewModel *userAccountModel = [WPUserAccountViewModel sharedInstance];
    WPUserAccount *userAccount = userAccountModel.userAccount;
    
    NSString *url = nil;
    NSDictionary *dict = nil;
    if (userAccount.user.phone.length)
    {
       //已绑定
        url = @"common/verifyCode.do";
        dict = @{@"phoneNum":self.phoneField.text,@"code":self.verifiedField.text};
    }
    else
    {
        //未绑定
        url = @"user/bindTel.do";
        dict = @{@"telephone":self.phoneField.text,@"codeInput":self.verifiedField.text};
    }
    
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self dismiss];
        if ([responseObject[@"result"] isEqualToString:@"success"])
        {
            self.isVerified = YES;
            [self showSuccessInfoWithStatus:@"验证成功"];
            //绑定手机号
            if (self.method)
            {
                //兑换收益
                WPBingYLVC *vc = [WPBingYLVC new];
                [self.navigationController pushViewController:vc animated:YES];
            }
            else
            {
                //兑换收益
                WPBingZFBVC *vc = [WPBingZFBVC new];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
        else
        {
            if ([responseObject[@"detail"] isEqualToString:@"codeInputError"])
            {
                [self showErrorInfoWithStatus:@"验证码错误"];
            }
            else if([responseObject[@"detail"] isEqualToString:@"areadyRegister"])
            {
                 [self showErrorInfoWithStatus:@"号码已经注册"];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self dismiss];
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

-(void)rightBtnDidClick
{
    [self backBtnDidClick];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
